package sporteam.web.client;

import java.util.ArrayList;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;

public class CompetitionWeb {


	private static GetCompetitionsFromDBServiceAsync getCompetitionsFromDBService = GWT
			.create(GetCompetitionsFromDBService.class);
	
	private static FlexTable competitionsTable = new FlexTable();

	public static HorizontalPanel createCompetitionDisplay() {
		HorizontalPanel panel = new HorizontalPanel();
		// Create table header
		competitionsTable.setText(0, 0, "Your Competitions:");
		
		//Add style to header
		competitionsTable.getRowFormatter().addStyleName(0,
						"runsTableHeader");
		
		//Add style to table
		competitionsTable.addStyleName("competitionTable");
		

		String access_token = Window.Location.getParameter("access_token");
		
		AsyncCallback<ArrayList<Competition>> callbackCompetitions = new AsyncCallback<ArrayList<Competition>>() {
			
			@Override
			public void onSuccess(ArrayList<Competition> result) {
				updateCompetitionsTable(result);
				
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		};
		
		
		
		getCompetitionsFromDBService.getCompetitions(access_token, callbackCompetitions);
		
		competitionsTable.addStyleName("competition-dispaly");
		
		Button createCompetitionButton = new Button();
		createCompetitionButton.setText("Create Competition");
		//createCompetitionButton.addClickHandler(Sporteam_web.getDefaultClickHandler(CreateCompetitionWeb.createCompetition()));
		
		//Assemble panel
		panel.add(createCompetitionButton);
		panel.add(competitionsTable);
		
		//Add style to panel
		panel.addStyleName("competitionDisplayPanel");
		//panel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		

		return panel;
	}

	private static void updateCompetitionsTable(ArrayList<Competition> competitions) {

		for (int i = 0; i < competitions.size(); i++) {
			competitionsTable.setWidget(i + 1, 0, new CompetitionWidget(competitions.get(i)));
		}

	}
}
